<template>
  <div class="file-viewer-page">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button type="primary" link @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        返回上一页
      </el-button>
    </div>

    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="file-title">{{ fileTitle }}</h1>
      <div class="file-meta">
        <span class="file-type">文件类型: {{ fileTypeText }}</span>
        <span class="file-size">{{ fileSize }}</span>
      </div>
    </div>

    <!-- 视频播放器区域 -->
    <div v-if="isVideo" class="video-viewer-container">
      <div class="viewer-controls">
        <el-button size="small" @click="downloadFile">
          <el-icon><Download /></el-icon>下载视频
        </el-button>
        <el-button size="small" @click="reloadVideo">
          <el-icon><Refresh /></el-icon>重新加载
        </el-button>

        <!-- 调试按钮 -->
        <el-button size="small" @click="testRefBinding" type="warning">
          测试Ref绑定
        </el-button>
      </div>

      <div class="viewer-content">
        <!-- 加载中提示 -->
        <div v-if="loading" class="loading-overlay">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>视频加载中...</span>
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="error-message">
          <el-alert type="error" :title="error" show-icon />
        </div>

        <!-- 视频播放器 -->
        <div v-if="!error" class="video-player-container">
          <video
              :ref="setVideoRef"
              :src="fileUrl"
              controls
              preload="metadata"
              width="100%"
              @loadedmetadata="onMetaLoaded"
              @canplay="handleVideoLoaded"
              @canplaythrough="handleVideoLoaded"
              @error="handleVideoError"
          >
            您的浏览器不支持视频播放
          </video>
        </div>
      </div>
    </div>

    <!-- 不支持文件类型 -->
    <div v-else class="unsupported-type">
      <el-result
          icon="warning"
          title="不支持的文件类型"
          :sub-title="`无法预览 ${fileType} 格式的文件`"
      >
        <template #extra>
          <el-button type="primary" @click="downloadFile">
            <el-icon><Download /></el-icon> 下载文件
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  ArrowLeft,
  Download,
  Loading,
  Refresh,
} from "@element-plus/icons-vue";

const route = useRoute();
const router = useRouter();

// 使用函数式 ref 绑定
const videoPlayer = ref(null);
const loading = ref(true);
const error = ref("");

const fileType = ref("mp4");
const fileTitle = ref("测试视频文件");
const fileTypeText = ref("视频文件");
const fileSize = ref("未知大小");
const fileUrl = ref("/pdfjs/test.mp4");

const isVideo = computed(() =>
    ["mp4", "webm", "ogg", "video"].includes(fileType.value.toLowerCase())
);

// 创建 ref 绑定函数
const setVideoRef = (el) => {
  if (el) {
    videoPlayer.value = el;
    console.log('视频元素已通过函数绑定:', videoPlayer.value);
    console.log('视频元素标签:', el.tagName, 'ID:', el.id, 'Class:', el.className);
  } else {
    console.log('视频元素已卸载');
    videoPlayer.value = null;
  }
};

// 测试 ref 绑定
const testRefBinding = () => {
  console.log('=== Ref绑定测试 ===');
  console.log('videoPlayer ref:', videoPlayer.value);
  console.log('通过选择器找到的视频元素:', document.querySelector('video'));

  if (videoPlayer.value) {
    console.log('视频src:', videoPlayer.value.src);
    console.log('视频duration:', videoPlayer.value.duration);
    console.log('视频尺寸:', videoPlayer.value.videoWidth, 'x', videoPlayer.value.videoHeight);
  }
};

// 返回上一页
const handleBack = () => {
  router.back();
};

// 下载视频
const downloadFile = () => {
  const link = document.createElement("a");
  link.href = fileUrl.value;
  link.download = fileTitle.value;
  link.click();
};

// 重新加载视频
const reloadVideo = () => {
  loading.value = true;
  error.value = "";

  console.log('重新加载视频，videoPlayer:', videoPlayer.value);

  if (videoPlayer.value) {
    videoPlayer.value.load();
  } else {
    // 如果 ref 绑定失败，尝试通过选择器获取
    const videoElement = document.querySelector('video');
    if (videoElement) {
      console.log('通过选择器重新加载视频');
      videoElement.load();
    } else {
      console.error('无法找到视频元素');
      ElMessage.error('无法找到视频元素');
    }
  }
};

// 元数据已加载
const onMetaLoaded = () => {
  console.log('视频元数据加载完成');

  if (videoPlayer.value) {
    const duration = videoPlayer.value.duration;
    const width = videoPlayer.value.videoWidth;
    const height = videoPlayer.value.videoHeight;
    console.log(`视频信息 - 时长: ${duration}s, 尺寸: ${width}x${height}`);

    // 更新文件大小信息
    if (duration && !isNaN(duration)) {
      fileSize.value = `${Math.round(duration)}秒`;
    }
  } else {
    // 如果 ref 绑定失败，尝试通过选择器获取
    const videoElement = document.querySelector('video');
    if (videoElement) {
      const duration = videoElement.duration;
      if (duration && !isNaN(duration)) {
        fileSize.value = `${Math.round(duration)}秒`;
      }
    }
  }
};

// 视频可播放
const handleVideoLoaded = () => {
  loading.value = false;
  // console.log('视频加载成功，videoPlayer:', videoPlayer.value);

  if (videoPlayer.value) {
    console.log('视频时长:', videoPlayer.value.duration);
    console.log('视频尺寸:', videoPlayer.value.videoWidth, 'x', videoPlayer.value.videoHeight);
  } else {
    console.log('videoPlayer 为 null，但视频已加载成功');
  }

  // ElMessage.success("视频加载成功");
};

// 视频加载错误
const handleVideoError = (e) => {
  loading.value = false;
  console.error('视频加载错误:', e);
  console.log('videoPlayer:', videoPlayer.value);

  let errorMessage = "视频加载失败";

  // 尝试通过不同方式获取视频元素来检查错误
  const videoElement = videoPlayer.value || document.querySelector('video');
  if (videoElement && videoElement.error) {
    const videoError = videoElement.error;

    switch(videoError.code) {
      case 1: errorMessage = "视频加载被中止"; break;
      case 2: errorMessage = "网络错误导致加载失败"; break;
      case 3: errorMessage = "视频解码错误"; break;
      case 4: errorMessage = "视频格式不支持"; break;
    }
  }

  error.value = errorMessage;
  ElMessage.error(error.value);
};

onMounted(async () => {
  console.log('FileViewerVideo 组件已挂载');

  const { type, title } = route.query;
  if (type) fileType.value = type;
  if (title) fileTitle.value = title;

  console.log('文件类型:', fileType.value);
  console.log('文件标题:', fileTitle.value);
  console.log('文件URL:', fileUrl.value);

  // 等待 DOM 完全渲染
  await nextTick();

  console.log('当前 videoPlayer ref:', videoPlayer.value);

  // 延迟检查，确保视频元素已经创建
  setTimeout(() => {
    console.log('延迟检查 videoPlayer ref:', videoPlayer.value);
    if (!videoPlayer.value) {
      console.warn('Ref绑定失败，尝试手动检查');
      const videoElement = document.querySelector('video');
      console.log('手动检查视频元素:', videoElement);
    }
  }, 100);
});
</script>

<style scoped>
.file-viewer-page {
  //max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.back-button {
  margin-bottom: 20px;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
  margin-bottom: 8px;
}

.file-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.video-viewer-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.viewer-controls {
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.viewer-content {
  position: relative;
  min-height: 400px;
}

.video-player-container {
  background: black;
  border-radius: 4px;
  overflow: hidden;
}

video {
  width: 100%;
  max-height: 600px;
  background: black;
  display: block;
}

.loading-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  color: #409eff;
  z-index: 10;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 10px;
  animation: spin 1s linear infinite;
}

.error-message {
  margin: 20px 0;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.unsupported-type {
  background: white;
  padding: 40px;
  border-radius: 8px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .file-viewer-page {
    padding: 16px;
  }

  .viewer-controls {
    flex-direction: column;
  }

  video {
    max-height: 400px;
  }
}
</style>
